const express = require('express');
const { Op, sequelize } = require('sequelize');
const { User, UserProfile, Activity, Badge, ActivityParticipant, Feed, UserFollow } = require('../models');
const { authenticateToken, optionalAuth } = require('../middleware/auth');
const { validatePagination } = require('../middleware/validation');

const router = express.Router();

// 获取用户列表
router.get('/', validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;
    const { search } = req.query;

    const whereConditions = {
      is_active: true
    };

    // 搜索用户
    if (search) {
      whereConditions[Op.or] = [
        { username: { [Op.like]: `%${search}%` } },
        { email: { [Op.like]: `%${search}%` } }
      ];
    }

    const { count, rows: users } = await User.findAndCountAll({
      where: whereConditions,
      attributes: ['id', 'username', 'avatar_url', 'bio', 'createdAt'],
      include: [
        {
          model: UserProfile,
          as: 'profile',
          attributes: ['interests', 'activity_frequency', 'social_level']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    res.json({
      users,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({
      error: '获取用户列表失败'
    });
  }
});

// 获取当前用户的个人资料
router.get('/profile', authenticateToken, async (req, res) => {
  try {
    const user = await User.findByPk(req.user.id, {
      attributes: ['id', 'username', 'email', 'avatar_url', 'bio', 'createdAt', 'last_login'],
      include: [
        {
          model: UserProfile,
          as: 'profile'
        }
      ]
    });

    if (!user) {
      return res.status(404).json({
        error: '用户不存在'
      });
    }

    // 获取用户统计信息
    const stats = await getUserStats(user.id);

    res.json({
      ...user.toJSON(),
      stats
    });
  } catch (error) {
    console.error('获取个人资料失败:', error);
    res.status(500).json({
      error: '获取个人资料失败'
    });
  }
});

// 更新当前用户的个人资料
router.put('/profile', authenticateToken, async (req, res) => {
  try {
    const { username, bio, email } = req.body;
    
    const user = await User.findByPk(req.user.id);
    if (!user) {
      return res.status(404).json({
        error: '用户不存在'
      });
    }

    // 检查用户名是否已被使用
    if (username && username !== user.username) {
      const existingUser = await User.findOne({ 
        where: { 
          username,
          id: { [Op.ne]: req.user.id }
        } 
      });
      if (existingUser) {
        return res.status(400).json({
          error: '用户名已被使用'
        });
      }
    }

    // 检查邮箱是否已被使用
    if (email && email !== user.email) {
      const existingUser = await User.findOne({ 
        where: { 
          email,
          id: { [Op.ne]: req.user.id }
        } 
      });
      if (existingUser) {
        return res.status(400).json({
          error: '邮箱已被使用'
        });
      }
    }

    await user.update({
      username: username || user.username,
      bio: bio !== undefined ? bio : user.bio,
      email: email || user.email
    });

    res.json({
      message: '个人资料更新成功',
      user: user.getPublicInfo()
    });
  } catch (error) {
    console.error('更新个人资料失败:', error);
    res.status(500).json({
      error: '更新个人资料失败'
    });
  }
});

// 获取当前用户参与的活动
router.get('/activities', authenticateToken, validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    const { count, rows: participations } = await ActivityParticipant.findAndCountAll({
      where: { user_id: req.user.id },
      include: [
        {
          model: Activity,
          as: 'activity',
          include: [
            {
              model: User,
              as: 'creator',
              attributes: ['id', 'username', 'avatar_url']
            }
          ]
        }
      ],
      order: [['registered_at', 'DESC']],
      limit,
      offset
    });

    const activities = participations.map(p => ({
      ...p.activity.toJSON(),
      participation_status: p.status,
      joined_at: p.registered_at
    }));

    res.json({
      activities,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取用户活动失败:', error);
    res.status(500).json({
      error: '获取用户活动失败'
    });
  }
});

// 获取当前用户的徽章
router.get('/badges', authenticateToken, validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 100;
    const offset = (page - 1) * limit;

    const { count, rows: badges } = await Badge.findAndCountAll({
      where: { user_id: req.user.id },
      include: [
        {
          model: Activity,
          as: 'activity',
          attributes: ['id', 'title', 'location', 'start_time']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    res.json({
      badges,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取用户徽章失败:', error);
    res.status(500).json({
      error: '获取用户徽章失败'
    });
  }
});

// 获取当前用户的动态
router.get('/feeds', authenticateToken, validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;
    
    const { count, rows: feeds } = await Feed.findAndCountAll({
      where: { user_id: req.user.id },
      include: [
        {
          model: Activity,
          as: 'activity',
          attributes: ['id', 'title', 'location', 'start_time'],
          required: false
        }
      ],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    res.json({
      feeds,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取用户动态失败:', error);
    res.status(500).json({
      error: '获取用户动态失败'
    });
  }
});

// 获取用户活跃度排行榜
router.get('/rankings/activity', validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    // 基于参与活动数量排行
    const rankings = await User.findAll({
      attributes: [
        'id',
        'username',
        'avatar_url',
        [sequelize.fn('COUNT', sequelize.col('participations.id')), 'activity_count']
      ],
      include: [
        {
          model: ActivityParticipant,
          as: 'participations',
          attributes: [],
          where: { status: 'attended' },
          required: false
        }
      ],
      group: ['User.id'],
      order: [[sequelize.fn('COUNT', sequelize.col('participations.id')), 'DESC']],
      limit,
      offset
    });

    res.json({
      rankings
    });
  } catch (error) {
    console.error('获取活跃度排行榜失败:', error);
    res.status(500).json({
      error: '获取活跃度排行榜失败'
    });
  }
});

// 获取徽章收集排行榜
router.get('/rankings/badges', validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    // 基于徽章数量排行
    const rankings = await User.findAll({
      attributes: [
        'id',
        'username',
        'avatar_url',
        [sequelize.fn('COUNT', sequelize.col('badges.id')), 'badge_count']
      ],
      include: [
        {
          model: Badge,
          as: 'badges',
          attributes: [],
          where: { status: 'minted' },
          required: false
        }
      ],
      group: ['User.id'],
      order: [[sequelize.fn('COUNT', sequelize.col('badges.id')), 'DESC']],
      limit,
      offset
    });

    res.json({
      rankings
    });
  } catch (error) {
    console.error('获取徽章排行榜失败:', error);
    res.status(500).json({
      error: '获取徽章排行榜失败'
    });
  }
});

// 获取用户详情 - 放在具体路径之后
router.get('/:id', optionalAuth, async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id, {
      attributes: ['id', 'username', 'avatar_url', 'bio', 'createdAt', 'last_login'],
      include: [
        {
          model: UserProfile,
          as: 'profile'
        }
      ]
    });

    if (!user) {
      return res.status(404).json({
        error: '用户不存在'
      });
    }

    // 获取用户统计信息
    const stats = await getUserStats(user.id);

    res.json({
      user,
      stats
    });
  } catch (error) {
    console.error('获取用户详情失败:', error);
    res.status(500).json({
      error: '获取用户详情失败'
    });
  }
});

// 更新用户画像
router.put('/:id/profile', authenticateToken, async (req, res) => {
  try {
    // 检查权限
    if (parseInt(req.params.id) !== req.user.id) {
      return res.status(403).json({
        error: '无权限修改其他用户的画像'
      });
    }

    const {
      interests,
      activity_preferences,
      location_preference,
      preferred_time_slots,
      activity_frequency,
      social_level
    } = req.body;

    let userProfile = await UserProfile.findOne({
      where: { user_id: req.user.id }
    });

    if (!userProfile) {
      userProfile = await UserProfile.create({
        user_id: req.user.id,
        interests: interests || [],
        activity_preferences: activity_preferences || {},
        location_preference,
        preferred_time_slots: preferred_time_slots || [],
        activity_frequency: activity_frequency || 'medium',
        social_level: social_level || 'ambivert'
      });
    } else {
      await userProfile.update({
        interests: interests !== undefined ? interests : userProfile.interests,
        activity_preferences: activity_preferences !== undefined ? activity_preferences : userProfile.activity_preferences,
        location_preference: location_preference !== undefined ? location_preference : userProfile.location_preference,
        preferred_time_slots: preferred_time_slots !== undefined ? preferred_time_slots : userProfile.preferred_time_slots,
        activity_frequency: activity_frequency || userProfile.activity_frequency,
        social_level: social_level || userProfile.social_level
      });
    }

    res.json({
      message: '用户画像更新成功',
      profile: userProfile
    });
  } catch (error) {
    console.error('更新用户画像失败:', error);
    res.status(500).json({
      error: '更新用户画像失败'
    });
  }
});

// 获取用户创建的活动
router.get('/:id/activities', validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    const { count, rows: activities } = await Activity.findAndCountAll({
      where: { created_by: req.params.id },
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'avatar_url']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    res.json({
      activities,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取用户活动失败:', error);
    res.status(500).json({
      error: '获取用户活动失败'
    });
  }
});

// 获取用户参与的活动
router.get('/:id/participations', validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;
    const { status } = req.query;

    const whereConditions = {
      user_id: req.params.id
    };

    if (status) {
      whereConditions.status = status;
    }

    const { count, rows: participations } = await ActivityParticipant.findAndCountAll({
      where: whereConditions,
      include: [
        {
          model: Activity,
          as: 'activity',
          include: [
            {
              model: User,
              as: 'creator',
              attributes: ['id', 'username', 'avatar_url']
            }
          ]
        }
      ],
      order: [['registered_at', 'DESC']],
      limit,
      offset
    });

    res.json({
      participations,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取用户参与活动失败:', error);
    res.status(500).json({
      error: '获取用户参与活动失败'
    });
  }
});

// 获取用户徽章
router.get('/:id/badges', validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 100;
    const offset = (page - 1) * limit;

    const { count, rows: badges } = await Badge.findAndCountAll({
      where: { user_id: req.params.id },
      include: [
        {
          model: Activity,
          as: 'activity',
          attributes: ['id', 'title', 'location', 'start_time']
        }
      ],
      order: [['minted_at', 'DESC']],
      limit,
      offset
    });

    res.json({
      badges,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取用户徽章失败:', error);
    res.status(500).json({
      error: '获取用户徽章失败'
    });
  }
});

// 设置钱包地址
router.put('/:id/wallet', authenticateToken, async (req, res) => {
  try {
    // 检查权限
    if (parseInt(req.params.id) !== req.user.id) {
      return res.status(403).json({
        error: '无权限修改其他用户的钱包地址'
      });
    }

    const { wallet_address } = req.body;

    if (!wallet_address) {
      return res.status(400).json({
        error: '钱包地址不能为空'
      });
    }

    // 验证钱包地址格式（简单验证）
    if (!/^0x[a-fA-F0-9]{40}$/.test(wallet_address)) {
      return res.status(400).json({
        error: '钱包地址格式无效'
      });
    }

    // 检查钱包地址是否已被使用
    const existingUser = await User.findOne({
      where: {
        wallet_address,
        id: { [Op.ne]: req.user.id }
      }
    });

    if (existingUser) {
      return res.status(400).json({
        error: '该钱包地址已被其他用户使用'
      });
    }

    const user = await User.findByPk(req.user.id);
    await user.update({ wallet_address });

    res.json({
      message: '钱包地址设置成功',
      wallet_address
    });
  } catch (error) {
    console.error('设置钱包地址失败:', error);
    res.status(500).json({
      error: '设置钱包地址失败'
    });
  }
});

// 获取用户统计信息
router.get('/:id/stats', async (req, res) => {
  try {
    const stats = await getUserStats(req.params.id);
    res.json(stats);
  } catch (error) {
    console.error('获取用户统计失败:', error);
    res.status(500).json({
      error: '获取用户统计失败'
    });
  }
});

// 关注用户
router.post('/:id/follow', authenticateToken, async (req, res) => {
  try {
    const targetUserId = parseInt(req.params.id);

    if (targetUserId === req.user.id) {
      return res.status(400).json({
        error: '不能关注自己'
      });
    }

    const targetUser = await User.findByPk(targetUserId);
    if (!targetUser) {
      return res.status(404).json({
        error: '用户不存在'
      });
    }

    // 检查是否已经关注
    const existingFollow = await UserFollow.findOne({
      where: {
        follower_id: req.user.id,
        following_id: targetUserId
      }
    });

    if (existingFollow) {
      return res.status(400).json({
        error: '已经关注了该用户'
      });
    }

    // 创建关注关系
    await UserFollow.create({
      follower_id: req.user.id,
      following_id: targetUserId,
      status: 'active'
    });

    res.json({
      message: '关注成功'
    });
  } catch (error) {
    console.error('关注用户失败:', error);
    res.status(500).json({
      error: '关注用户失败'
    });
  }
});

// 取消关注用户
router.delete('/:id/follow', authenticateToken, async (req, res) => {
  try {
    const targetUserId = parseInt(req.params.id);

    const follow = await UserFollow.findOne({
      where: {
        follower_id: req.user.id,
        following_id: targetUserId
      }
    });

    if (!follow) {
      return res.status(404).json({
        error: '未关注该用户'
      });
    }

    await follow.destroy();

    res.json({
      message: '取消关注成功'
    });
  } catch (error) {
    console.error('取消关注失败:', error);
    res.status(500).json({
      error: '取消关注失败'
    });
  }
});

// 获取用户关注列表
router.get('/:id/following', validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    const { count, rows: follows } = await UserFollow.findAndCountAll({
      where: { 
        follower_id: req.params.id,
        status: 'active'
      },
      include: [
        {
          model: User,
          as: 'followingUser',
          attributes: ['id', 'username', 'avatar_url', 'bio']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    const followingUsers = follows.map(follow => follow.followingUser);

    res.json({
      users: followingUsers,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取关注列表失败:', error);
    res.status(500).json({
      error: '获取关注列表失败'
    });
  }
});

// 获取用户粉丝列表
router.get('/:id/followers', validatePagination, async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    const { count, rows: follows } = await UserFollow.findAndCountAll({
      where: { 
        following_id: req.params.id,
        status: 'active'
      },
      include: [
        {
          model: User,
          as: 'follower',
          attributes: ['id', 'username', 'avatar_url', 'bio']
        }
      ],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });

    const followers = follows.map(follow => follow.follower);

    res.json({
      users: followers,
      pagination: {
        page,
        limit,
        total: count,
        totalPages: Math.ceil(count / limit)
      }
    });
  } catch (error) {
    console.error('获取粉丝列表失败:', error);
    res.status(500).json({
      error: '获取粉丝列表失败'
    });
  }
});

// 检查关注状态
router.get('/:id/follow-status', authenticateToken, async (req, res) => {
  try {
    const targetUserId = parseInt(req.params.id);

    if (targetUserId === req.user.id) {
      return res.json({
        isFollowing: false,
        isSelf: true
      });
    }

    const follow = await UserFollow.findOne({
      where: {
        follower_id: req.user.id,
        following_id: targetUserId,
        status: 'active'
      }
    });

    res.json({
      isFollowing: !!follow,
      isSelf: false
    });
  } catch (error) {
    console.error('检查关注状态失败:', error);
    res.status(500).json({
      error: '检查关注状态失败'
    });
  }
});

// 辅助函数：获取用户统计信息
async function getUserStats(userId) {
  const [
    createdActivitiesCount,
    participatedActivitiesCount,
    badgesCount,
    attendedActivitiesCount,
    followingCount,
    followersCount
  ] = await Promise.all([
    Activity.count({ where: { created_by: userId } }),
    ActivityParticipant.count({ where: { user_id: userId } }),
    Badge.count({ where: { user_id: userId, status: 'minted' } }),
    ActivityParticipant.count({ where: { user_id: userId, status: 'attended' } }),
    UserFollow.count({ where: { follower_id: userId, status: 'active' } }),
    UserFollow.count({ where: { following_id: userId, status: 'active' } })
  ]);

  return {
    createdActivitiesCount,
    participatedActivitiesCount,
    badgesCount,
    attendedActivitiesCount,
    followingCount,
    followersCount,
    attendanceRate: participatedActivitiesCount > 0 
      ? (attendedActivitiesCount / participatedActivitiesCount * 100).toFixed(1)
      : 0
  };
}

module.exports = router; 